// Popup script for the extension
let currentTab = 'practices';
let longevityContent = [];
let userContent = [];
let favorites = [];
let reminders = [];
let rssArticles = [];
let timerInterval = null;

// Initialize on load
document.addEventListener('DOMContentLoaded', async () => {
  await initialize();
  setupEventListeners();
  loadTab(currentTab);
});

// Clean up timer interval when popup closes
window.addEventListener('beforeunload', () => {
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
});

async function initialize() {
  // Initialize storage
  await StorageManager.initialize();
  
  // Load default reminders if first run
  const data = await chrome.storage.local.get(['reminders', 'initialized']);
  if (!data.reminders || data.reminders.length === 0) {
    // Load default reminders
    if (typeof DEFAULT_REMINDERS !== 'undefined') {
      const remindersWithDefaults = DEFAULT_REMINDERS.map(r => ({
        ...r,
        lastTriggered: null
      }));
      await chrome.storage.local.set({ reminders: remindersWithDefaults });
      reminders = remindersWithDefaults;
    } else {
      reminders = [];
    }
  } else {
    reminders = data.reminders;
  }
  
  // Clear initialized reminders set when reloading
  initializedReminders.clear();
  
  // Load longevity content
  if (typeof LONGEVITY_CONTENT !== 'undefined') {
    longevityContent = LONGEVITY_CONTENT;
  }
  
  // Load user content and favorites
  userContent = await StorageManager.getUserContent();
  favorites = await StorageManager.getFavorites();
  
  // Load RSS articles
  rssArticles = await StorageManager.getRSSArticles();
  
  // If no RSS articles, trigger a fetch
  if (rssArticles.length === 0) {
    try {
      await StorageManager.refreshRSSFeed();
      rssArticles = await StorageManager.getRSSArticles();
    } catch (error) {
      console.error('Error fetching RSS feed:', error);
    }
  }
  
  // Load and apply settings
  const settings = await StorageManager.getSettings();
  const themeSelect = document.getElementById('themeSelect');
  const soundSelect = document.getElementById('soundSelect');
  const notificationsEnabled = document.getElementById('notificationsEnabled');
  const badgeEnabled = document.getElementById('badgeEnabled');
  
  if (themeSelect) themeSelect.value = settings.theme || 'dark';
  if (soundSelect) soundSelect.value = settings.notificationSound || 'beep';
  if (notificationsEnabled) notificationsEnabled.checked = settings.notificationsEnabled !== false;
  if (badgeEnabled) badgeEnabled.checked = settings.badgeEnabled !== false;
  applyTheme(settings.theme || 'dark');
  
  // Clear badge when popup opens
  chrome.runtime.sendMessage({ action: 'clearBadge' });
  chrome.action.setBadgeText({ text: '' });
}

function setupEventListeners() {
  // Bottom navigation switching
  document.querySelectorAll('.nav-item').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const tab = e.currentTarget.dataset.tab;
      switchTab(tab);
    });
  });
  
  // Add content button
  const addContentBtn = document.getElementById('addContentBtn');
  if (addContentBtn) {
    addContentBtn.addEventListener('click', () => {
      document.getElementById('addContentModal').style.display = 'block';
    });
  }
  
  // Add reminder button
  const addReminderBtn = document.getElementById('addReminderBtn');
  if (addReminderBtn) {
    addReminderBtn.addEventListener('click', () => {
      document.getElementById('addReminderModal').style.display = 'block';
    });
  }
  
  // Refresh RSS button
  const refreshRSSBtn = document.getElementById('refreshRSSBtn');
  if (refreshRSSBtn) {
    refreshRSSBtn.addEventListener('click', async () => {
      refreshRSSBtn.disabled = true;
      refreshRSSBtn.textContent = '⏳';
      try {
        await StorageManager.refreshRSSFeed();
        rssArticles = await StorageManager.getRSSArticles();
        renderNews();
      } catch (error) {
        console.error('Error refreshing RSS:', error);
        alert('Failed to refresh news. Please try again later.');
      } finally {
        refreshRSSBtn.disabled = false;
        refreshRSSBtn.textContent = '🔄';
      }
    });
  }
  
  // AI Activate button
  const activateAI = document.getElementById('activateAI');
  if (activateAI) {
    activateAI.addEventListener('click', () => {
      // TODO: Implement AI activation logic
      alert('AI activation feature coming soon!');
    });
  }
  
  // Modal close buttons
  document.querySelectorAll('.close').forEach(closeBtn => {
    closeBtn.addEventListener('click', (e) => {
      e.target.closest('.modal').style.display = 'none';
    });
  });
  
  // Click outside modal to close
  window.addEventListener('click', (e) => {
    if (e.target.classList.contains('modal')) {
      e.target.style.display = 'none';
    }
  });
  
  // Add content form
  document.getElementById('addContentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('contentTitle').value;
    const link = document.getElementById('contentLink').value;
    const description = document.getElementById('contentDescription').value;
    const category = document.getElementById('contentCategory').value;
    
    await StorageManager.addUserContent({ title, link, description, category });
    document.getElementById('addContentModal').style.display = 'none';
    document.getElementById('addContentForm').reset();
    await initialize();
    loadTab(currentTab);
  });
  
  // Add reminder form
  document.getElementById('addReminderForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('reminderTitle').value;
    const description = document.getElementById('reminderDescription').value;
    const frequency = parseInt(document.getElementById('reminderFrequency').value);
    const enabled = document.getElementById('reminderEnabled').checked;
    
    await StorageManager.addCustomReminder({ title, description, frequency, enabled });
    document.getElementById('addReminderModal').style.display = 'none';
    document.getElementById('addReminderForm').reset();
    await initialize();
    loadTab('reminders');
  });
  
  // Clear badge button (removed from UI, badge clears automatically on popup open)

  // Settings event listeners
  const themeSelect = document.getElementById('themeSelect');
  const soundSelect = document.getElementById('soundSelect');
  const notificationsEnabled = document.getElementById('notificationsEnabled');
  const badgeEnabled = document.getElementById('badgeEnabled');

  if (themeSelect) {
    themeSelect.addEventListener('change', async (e) => {
      const theme = e.target.value;
      await StorageManager.updateSettings({ theme });
      applyTheme(theme);
    });
  }

  if (soundSelect) {
    soundSelect.addEventListener('change', async (e) => {
      const notificationSound = e.target.value;
      await StorageManager.updateSettings({ notificationSound });
    });
  }

  if (notificationsEnabled) {
    notificationsEnabled.addEventListener('change', async (e) => {
      await StorageManager.updateSettings({ notificationsEnabled: e.target.checked });
    });
  }

  if (badgeEnabled) {
    badgeEnabled.addEventListener('change', async (e) => {
      await StorageManager.updateSettings({ badgeEnabled: e.target.checked });
    });
  }
}

function switchTab(tab) {
  currentTab = tab;
  
  // Clear timer if switching away from reminders tab
  if (tab !== 'reminders' && timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
  
  // Update navigation buttons
  document.querySelectorAll('.nav-item').forEach(btn => {
    btn.classList.remove('active');
    if (btn.dataset.tab === tab) {
      btn.classList.add('active');
    }
  });
  
  // Show/hide main content sections
  const mainContent = document.querySelector('.main-content');
  const practicesList = document.getElementById('practices-list');
  const aiCard = document.querySelector('.ai-card');
  const sectionTitle = document.querySelector('.section-title');
  
  // Hide all tab contents
  document.querySelectorAll('.tab-content').forEach(content => {
    content.classList.remove('active');
    content.classList.add('hidden');
  });
  
  if (tab === 'practices') {
    // Show practices view
    if (practicesList) practicesList.style.display = 'block';
    if (aiCard) aiCard.style.display = 'block';
    if (sectionTitle) {
      sectionTitle.textContent = 'Auto-displayed practices';
      sectionTitle.style.display = 'block';
    }
  } else {
    // Hide practices view, show tab content
    if (practicesList) practicesList.style.display = 'none';
    if (aiCard) aiCard.style.display = 'none';
    if (sectionTitle) sectionTitle.style.display = 'none';
    
    const tabContent = document.getElementById(`${tab}-tab`);
    if (tabContent) {
      tabContent.classList.remove('hidden');
      tabContent.classList.add('active');
    }
  }
  
  loadTab(tab);
}

function loadTab(tab) {
  switch(tab) {
    case 'practices':
      renderPractices();
      break;
    case 'content':
      renderContent();
      break;
    case 'reminders':
      renderReminders();
      break;
    case 'favorites':
      renderFavorites();
      break;
    case 'news':
      renderNews();
      break;
    case 'settings':
      renderSettings();
      break;
  }
}

function renderPractices() {
  const container = document.getElementById('practices-list');
  if (!container) return;
  
  // Default practices matching the image design - always show these
  const defaultPractices = [
    { id: 'breathing', name: 'Breathing', enabled: true },
    { id: 'mood-journal', name: 'Mood Journal', enabled: true },
    { id: 'warm-ups', name: 'Warm-Up\'s', enabled: true }
  ];
  
  // Map to reminder states if they exist
  const practices = defaultPractices.map(practice => {
    // Try to find matching reminder
    let matchingReminder = null;
    if (practice.id === 'breathing') {
      matchingReminder = reminders.find(r => r.id === 'deep-breathing');
    } else if (practice.id === 'mood-journal') {
      matchingReminder = reminders.find(r => r.id === 'meditation');
    } else if (practice.id === 'warm-ups') {
      matchingReminder = reminders.find(r => r.id === 'movement');
    }
    
    return {
      id: practice.id,
      name: practice.name,
      enabled: matchingReminder ? matchingReminder.enabled : practice.enabled,
      reminderId: matchingReminder ? matchingReminder.id : null
    };
  });
  
  container.innerHTML = practices.map(practice => `
    <div class="practice-item">
      <span class="practice-name">${practice.name}</span>
      <label class="toggle-switch">
        <input type="checkbox" class="practice-toggle" data-id="${practice.id}" data-reminder-id="${practice.reminderId || ''}" ${practice.enabled ? 'checked' : ''}>
        <span class="toggle-slider"></span>
      </label>
      <button class="play-btn" data-id="${practice.id}" title="Play ${practice.name}"></button>
    </div>
  `).join('');
  
  // Add toggle listeners
  container.querySelectorAll('.practice-toggle').forEach(toggle => {
    toggle.addEventListener('change', async (e) => {
      const practiceId = e.target.dataset.id;
      const reminderId = e.target.dataset.reminderId;
      
      // Update matching reminder if it exists
      if (reminderId) {
        const reminder = reminders.find(r => r.id === reminderId);
        if (reminder) {
          await StorageManager.updateReminder(reminderId, { enabled: e.target.checked });
          reminders = await StorageManager.getReminders();
        }
      }
      // Store practice preference locally for practices without reminders
      // TODO: Could store practice preferences separately in storage
    });
  });
  
  // Add play button listeners
  container.querySelectorAll('.play-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const practiceId = e.target.dataset.id || e.target.closest('.play-btn')?.dataset.id;
      
      // Handle breathing exercise - open in new tab
      if (practiceId === 'breathing' || practiceId === 'deep-breathing') {
        chrome.tabs.create({ url: chrome.runtime.getURL('breathing.html') });
      } else {
        // TODO: Implement other practice functionalities
        console.log('Playing practice:', practiceId);
      }
    });
  });
  
  // Also add a dedicated breathing mode card if not already shown
  const breathingPractice = practices.find(p => p.id === 'breathing' || p.id === 'deep-breathing');
  if (breathingPractice) {
    // Add a prominent breathing card
    const breathingCard = document.createElement('div');
    breathingCard.className = 'practice-card breathing-practice';
    breathingCard.innerHTML = `
      <div class="practice-icon">🌬️</div>
      <div class="practice-content">
        <h3>Breathing Exercise</h3>
        <p>5-minute guided breathing exercise with timer. Follow the 4-7-8 technique for stress relief and HRV improvement.</p>
        <button class="practice-btn" id="startBreathingBtn">Start Breathing Mode</button>
      </div>
    `;
    container.insertBefore(breathingCard, container.firstChild);
    
    // Add click listener for breathing mode button
    const breathingBtn = document.getElementById('startBreathingBtn');
    if (breathingBtn) {
      breathingBtn.addEventListener('click', () => {
        chrome.tabs.create({ url: chrome.runtime.getURL('breathing.html') });
      });
    }
  }
}

function renderContent() {
  const container = document.getElementById('content-list');
  const allContent = [...longevityContent, ...userContent];
  
  if (allContent.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No content available. Add some longevity information!</p></div>';
    return;
  }
  
  container.innerHTML = allContent.map(item => createContentCard(item)).join('');
  
  // Add favorite button listeners
  container.querySelectorAll('.favorite-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.id;
      const isFavorite = await StorageManager.isFavorite(id);
      
      if (isFavorite) {
        await StorageManager.removeFavorite(id);
      } else {
        await StorageManager.addFavorite(id);
      }
      
      favorites = await StorageManager.getFavorites();
      renderContent();
    });
  });
  
  // Add click listeners to open links
  container.querySelectorAll('.content-card').forEach(card => {
    card.addEventListener('click', (e) => {
      if (!e.target.classList.contains('favorite-btn')) {
        const link = card.dataset.link;
        if (link) {
          chrome.tabs.create({ url: link });
        }
      }
    });
  });
}

function renderFavorites() {
  const container = document.getElementById('favorites-list');
  const allContent = [...longevityContent, ...userContent];
  const favoriteItems = allContent.filter(item => favorites.includes(item.id));
  
  if (favoriteItems.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No favorites yet. Star items to add them here!</p></div>';
    return;
  }
  
  container.innerHTML = favoriteItems.map(item => createContentCard(item)).join('');
  
  // Add favorite button listeners
  container.querySelectorAll('.favorite-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.id;
      await StorageManager.removeFavorite(id);
      favorites = await StorageManager.getFavorites();
      renderFavorites();
    });
  });
  
  // Add click listeners
  container.querySelectorAll('.content-card').forEach(card => {
    card.addEventListener('click', (e) => {
      if (!e.target.classList.contains('favorite-btn')) {
        const link = card.dataset.link;
        if (link) {
          chrome.tabs.create({ url: link });
        }
      }
    });
  });
}

function renderReminders() {
  const container = document.getElementById('reminders-list');
  
  if (reminders.length === 0) {
    container.innerHTML = '<div class="empty-state"><p>No reminders configured. Add one to get started!</p></div>';
    // Clear timer if no reminders
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
    // Clear initialized reminders set
    initializedReminders.clear();
    return;
  }
  
  container.innerHTML = reminders.map(reminder => createReminderItem(reminder)).join('');
  
  // Start/restart timer interval
  startTimerInterval();
  
  // Add toggle listeners
  container.querySelectorAll('.reminder-toggle').forEach(toggle => {
    toggle.addEventListener('change', async (e) => {
      const reminderId = e.target.dataset.id;
      const enabled = e.target.checked;
      const reminder = reminders.find(r => r.id === reminderId);
      
      // Initialize lastTriggered when enabling a reminder that has never been triggered
      const updates = { enabled };
      if (enabled && !reminder.lastTriggered) {
        updates.lastTriggered = Date.now();
      }
      
      await StorageManager.updateReminder(reminderId, updates);
      reminders = await StorageManager.getReminders();
      renderReminders();
    });
  });
  
  // Add frequency edit listeners
  container.querySelectorAll('.frequency').forEach(freq => {
    freq.addEventListener('click', (e) => {
      e.stopPropagation();
      const reminderId = freq.dataset.id;
      showFrequencyEditor(reminderId, freq);
    });
  });
  
  // Add quick preset listeners
  container.querySelectorAll('.frequency-preset').forEach(preset => {
    preset.addEventListener('click', async (e) => {
      e.stopPropagation();
      const reminderId = preset.dataset.id;
      const minutes = parseInt(preset.dataset.minutes);
      await StorageManager.updateReminder(reminderId, { frequency: minutes });
      reminders = await StorageManager.getReminders();
      renderReminders();
    });
  });
  
  // Handle frequency input submission
  container.querySelectorAll('.frequency-input').forEach(input => {
    input.addEventListener('blur', async (e) => {
      const reminderId = input.dataset.id;
      const value = parseInt(input.value);
      if (!isNaN(value) && value > 0) {
        await StorageManager.updateReminder(reminderId, { frequency: value });
        reminders = await StorageManager.getReminders();
        renderReminders();
      } else {
        renderReminders(); // Re-render to cancel edit
      }
    });
    
    input.addEventListener('keydown', async (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        const reminderId = input.dataset.id;
        const value = parseInt(input.value);
        if (!isNaN(value) && value > 0) {
          await StorageManager.updateReminder(reminderId, { frequency: value });
          reminders = await StorageManager.getReminders();
          renderReminders();
        } else {
          renderReminders(); // Re-render to cancel edit
        }
      } else if (e.key === 'Escape') {
        renderReminders(); // Cancel edit
      }
    });
  });
}

function startTimerInterval() {
  // Clear existing interval if any
  if (timerInterval) {
    clearInterval(timerInterval);
  }
  
  // Update timers immediately
  updateAllTimers();
  
  // Update timers every second
  timerInterval = setInterval(() => {
    updateAllTimers();
  }, 1000);
}

// Track which reminders we've initialized to avoid repeated storage writes
const initializedReminders = new Set();
// Track previous state of reminders to detect transitions to "Due now"
const reminderPreviousState = new Map();

function updateAllTimers() {
  reminders.forEach(reminder => {
    const timerElement = document.querySelector(`.reminder-timer[data-id="${reminder.id}"]`);
    if (timerElement) {
      // Initialize lastTriggered for enabled reminders that have never been triggered
      if (reminder.enabled && !reminder.lastTriggered && !initializedReminders.has(reminder.id)) {
        const now = Date.now();
        reminder.lastTriggered = now;
        initializedReminders.add(reminder.id);
        // Update in storage asynchronously (only once)
        StorageManager.updateReminder(reminder.id, { lastTriggered: now }).catch(() => {
          // Silently fail if storage update fails
        });
      }
      
      const timeText = calculateTimeUntilNext(reminder);
      const wasDue = reminderPreviousState.get(reminder.id) || false;
      const isDue = timeText === 'Due now';
      
      // Detect transition from "not due" to "due"
      if (!wasDue && isDue && reminder.enabled) {
        // Notify background script to play sound and show notification
        chrome.runtime.sendMessage({
          action: 'reminderDue',
          reminderId: reminder.id,
          reminder: reminder
        }).catch(() => {
          // Silently fail if message fails
        });
      }
      
      // Update previous state
      reminderPreviousState.set(reminder.id, isDue);
      timerElement.textContent = timeText;
    }
  });
}

function calculateTimeUntilNext(reminder) {
  if (!reminder.enabled) {
    return 'Disabled';
  }
  
  // This should never happen if updateAllTimers runs first, but handle it just in case
  if (!reminder.lastTriggered) {
    return 'Starting...';
  }
  
  const now = Date.now();
  const frequencyMs = reminder.frequency * 60 * 1000; // Convert minutes to milliseconds
  const nextTriggerTime = reminder.lastTriggered + frequencyMs;
  const timeRemaining = nextTriggerTime - now;
  
  // If time has passed, show "Due now"
  if (timeRemaining <= 0) {
    return 'Due now';
  }
  
  // Format time remaining
  const hours = Math.floor(timeRemaining / (1000 * 60 * 60));
  const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
  
  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  } else if (minutes > 0) {
    return `${minutes}m ${seconds}s`;
  } else {
    return `${seconds}s`;
  }
}

function createContentCard(item) {
  const isFavorite = favorites.includes(item.id);
  const link = item.link || (item.references && item.references[0]?.url) || '#';
  
  return `
    <div class="content-card" data-link="${link}">
      <h3>
        ${item.title}
        <button class="favorite-btn ${isFavorite ? 'active' : ''}" data-id="${item.id}">
          ${isFavorite ? '⭐' : '☆'}
        </button>
      </h3>
      <span class="category">${item.category || 'General'}</span>
      <p>${item.description || ''}</p>
      ${item.references ? `
        <div class="references">
          <strong>References:</strong>
          ${item.references.map(ref => `
            <a href="${ref.url}" target="_blank" onclick="event.stopPropagation()">${ref.text}</a>
          `).join('')}
        </div>
      ` : ''}
    </div>
  `;
}

function createReminderItem(reminder) {
  const frequencyText = reminder.frequency >= 1440 
    ? 'Daily' 
    : reminder.frequency >= 60 
      ? `${reminder.frequency / 60} ${reminder.frequency / 60 === 1 ? 'hour' : 'hours'}` 
      : `${reminder.frequency} ${reminder.frequency === 1 ? 'minute' : 'minutes'}`;
  
  // Format frequency display text
  const frequencyDisplay = reminder.frequency >= 1440 
    ? 'Daily' 
    : `Every ${frequencyText}`;
  
  const timeUntilNext = calculateTimeUntilNext(reminder);
  
  return `
    <div class="reminder-item">
      <div class="reminder-info">
        <div class="reminder-header">
          <h3 title="${reminder.description || ''}">
            <span>${reminder.icon || '⏰'}</span>
            ${reminder.title}
          </h3>
          <label class="toggle-switch">
            <input type="checkbox" class="reminder-toggle" data-id="${reminder.id}" ${reminder.enabled ? 'checked' : ''}>
            <span class="toggle-slider"></span>
          </label>
        </div>
        <div class="reminder-footer">
          <div class="frequency-container">
            <span class="frequency" data-id="${reminder.id}" title="Click to edit frequency">
              ${frequencyDisplay}
              <span class="edit-icon">✏️</span>
            </span>
          </div>
          <div class="reminder-timer" data-id="${reminder.id}">${timeUntilNext}</div>
        </div>
      </div>
    </div>
  `;
}

function showFrequencyEditor(reminderId, frequencyElement) {
  const reminder = reminders.find(r => r.id === reminderId);
  if (!reminder) return;
  
  const container = frequencyElement.closest('.frequency-container');
  const currentFrequency = reminder.frequency;
  
  // Preset options
  const presets = [
    { label: '15m', minutes: 15 },
    { label: '30m', minutes: 30 },
    { label: '1h', minutes: 60 },
    { label: '2h', minutes: 120 },
    { label: '3h', minutes: 180 },
    { label: '4h', minutes: 240 }
  ];
  
  container.innerHTML = `
    <div class="frequency-editor">
      <div class="frequency-presets">
        ${presets.map(preset => `
          <button type="button" class="frequency-preset ${currentFrequency === preset.minutes ? 'active' : ''}" 
                  data-id="${reminderId}" 
                  data-minutes="${preset.minutes}">
            ${preset.label}
          </button>
        `).join('')}
      </div>
      <div class="frequency-custom">
        <input type="number" 
               class="frequency-input" 
               data-id="${reminderId}" 
               value="${currentFrequency}" 
               min="1" 
               placeholder="Minutes"
               autofocus>
        <span class="frequency-unit">minutes</span>
      </div>
    </div>
  `;
  
  // Focus the input and attach event listeners
  const input = container.querySelector('.frequency-input');
  if (input) {
    input.focus();
    input.select();
    
    // Handle blur event
    input.addEventListener('blur', async (e) => {
      const value = parseInt(input.value);
      if (!isNaN(value) && value > 0) {
        await StorageManager.updateReminder(reminderId, { frequency: value });
        reminders = await StorageManager.getReminders();
        renderReminders();
      } else {
        renderReminders(); // Re-render to cancel edit
      }
    });
    
    // Handle keydown events (Enter and Escape)
    input.addEventListener('keydown', async (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        const value = parseInt(input.value);
        if (!isNaN(value) && value > 0) {
          await StorageManager.updateReminder(reminderId, { frequency: value });
          reminders = await StorageManager.getReminders();
          renderReminders();
        } else {
          renderReminders(); // Re-render to cancel edit
        }
      } else if (e.key === 'Escape') {
        renderReminders(); // Cancel edit
      }
    });
  }
  
  // Attach preset button listeners
  container.querySelectorAll('.frequency-preset').forEach(preset => {
    preset.addEventListener('click', async (e) => {
      e.stopPropagation();
      e.preventDefault();
      const minutes = parseInt(preset.dataset.minutes);
      if (isNaN(minutes) || minutes <= 0) return;
      
      // Update the reminder in storage
      await StorageManager.updateReminder(reminderId, { frequency: minutes });
      
      // Refresh reminders array from storage to get the latest data
      reminders = await StorageManager.getReminders();
      
      // Update the local reminder object
      const updatedReminder = reminders.find(r => r.id === reminderId);
      if (updatedReminder) {
        // Update active state of preset buttons - remove active from all, then add to clicked one
        container.querySelectorAll('.frequency-preset').forEach(btn => {
          const btnMinutes = parseInt(btn.dataset.minutes);
          if (btnMinutes === minutes) {
            btn.classList.add('active');
          } else {
            btn.classList.remove('active');
          }
        });
        
        // Update the input field value
        const input = container.querySelector('.frequency-input');
        if (input) {
          input.value = minutes;
        }
        
        // Update the frequency display text that's shown outside the editor
        // We need to find the reminder item and update its frequency display
        const reminderItem = container.closest('.reminder-item');
        if (reminderItem) {
          // The frequency display is in the footer, but it's replaced by the editor
          // So we'll update it when the editor closes, but for now update the timer if needed
          // The main thing is the preset buttons show the active state
        }
      }
    });
  });
}

function renderNews() {
  const container = document.getElementById('news-list');
  if (!container) return;
  
  if (rssArticles.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <p>No news articles available.</p>
        <p style="font-size: 12px; margin-top: 8px; color: rgba(255, 255, 255, 0.5);">
          Click the refresh button to load articles from Lifespan.io
        </p>
      </div>
    `;
    return;
  }
  
  // Sort articles by timestamp (newest first)
  const sortedArticles = [...rssArticles].sort((a, b) => {
    const dateA = a.pubDate ? new Date(a.pubDate).getTime() : a.timestamp || 0;
    const dateB = b.pubDate ? new Date(b.pubDate).getTime() : b.timestamp || 0;
    return dateB - dateA;
  });
  
  container.innerHTML = sortedArticles.map(article => createNewsCard(article)).join('');
  
  // Add click listeners to open links
  container.querySelectorAll('.news-card').forEach(card => {
    card.addEventListener('click', (e) => {
      if (!e.target.classList.contains('favorite-btn')) {
        const link = card.dataset.link;
        if (link) {
          chrome.tabs.create({ url: link });
        }
      }
    });
  });
  
  // Add favorite button listeners
  container.querySelectorAll('.favorite-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.id;
      const isFavorite = await StorageManager.isFavorite(id);
      
      if (isFavorite) {
        await StorageManager.removeFavorite(id);
      } else {
        await StorageManager.addFavorite(id);
      }
      
      favorites = await StorageManager.getFavorites();
      renderNews();
    });
  });
}

function createNewsCard(article) {
  const isFavorite = favorites.includes(article.id);
  const link = article.link || '#';
  
  // Format date
  let dateText = '';
  if (article.pubDate) {
    try {
      const date = new Date(article.pubDate);
      const now = new Date();
      const diffMs = now - date;
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        dateText = 'Today';
      } else if (diffDays === 1) {
        dateText = 'Yesterday';
      } else if (diffDays < 7) {
        dateText = `${diffDays} days ago`;
      } else {
        dateText = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined });
      }
    } catch (e) {
      dateText = '';
    }
  }
  
  // Get categories
  const categories = article.categories || [];
  const categoryText = categories.length > 0 ? categories[0] : 'News';
  
  return `
    <div class="news-card" data-link="${link}">
      ${article.imageUrl ? `
        <div class="news-image">
          <img src="${article.imageUrl}" alt="${article.title}" onerror="this.style.display='none'">
        </div>
      ` : ''}
      <div class="news-content">
        <div class="news-header">
          <span class="news-category">${categoryText}</span>
          ${dateText ? `<span class="news-date">${dateText}</span>` : ''}
        </div>
        <h3>
          ${article.title}
          <button class="favorite-btn ${isFavorite ? 'active' : ''}" data-id="${article.id}">
            ${isFavorite ? '⭐' : '☆'}
          </button>
        </h3>
        ${article.description ? `<p class="news-description">${article.description}</p>` : ''}
        <div class="news-footer">
          <span class="news-source">${article.source || 'Lifespan.io'}</span>
        </div>
      </div>
    </div>
  `;
}

function renderSettings() {
  // Settings are already rendered in HTML, just ensure they're up to date
  // This function is called when switching to settings tab
}

function applyTheme(theme) {
  document.body.setAttribute('data-theme', theme);
  // Also apply to parent window if in extension popup context
  if (window.parent !== window) {
    try {
      window.parent.document.body.setAttribute('data-theme', theme);
    } catch (e) {
      // Cross-origin restriction, ignore
    }
  }
}

